   

#include "pwmin.h"
#include "uart2.h"

state_t pwmin_state;
	
volatile u08 pwmin_read_flag;
	
unsigned int pwmin_count_Up;
unsigned int pwmin_count_Down;
	
u08 current_channel;

u08 pwmin_channel_type[8] = {0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80};

/************************************************************\
|                      pwinInit()                          |
\************************************************************/
void pwminInit(void)
{
	outb(DDRF,0x00); //make all of PORTF input
	outb(TCCR2,0x01); // no prescalar
	outb(OCR2,10); // 1/ 14,745MHz * 10 = 0.67 us sample period
	outb(TCNT2,0); //zero out the timer, start over
}

/************************************************************\
|                      PWMIN_Read()                          |
\************************************************************/
unsigned int PWMIN_Read(u08 channel)
{
	// set initial values
	pwmin_count_Up = 0;
	pwmin_count_Down = 0;
	pwmin_read_flag = 0;
	pwmin_state = INIT;
	current_channel = pwmin_channel_type[channel];
				
	uart0InitBuffers();

	sbi(TIMSK,OCIE2); //enable timer0 compare irq (start the counting)

	// Wait for the timer to sample a PWM pulse

	while(pwmin_read_flag == 0);

	return pwmin_count_Up;
}

SIGNAL(SIG_OUTPUT_COMPARE2)
{
	uint8_t portf_status;
	
	outb(TCNT2,0); //zero out the timer, start over
	
	asm volatile("nop;");

	portf_status=inb(PINF) & current_channel; //read proper value of PORTF

	switch(pwmin_state)
	{
		   // Initial state --> rising edge scan
		case INIT:
			if (portf_status == 0)
			{				
				pwmin_state = RISING_EDGE_SCAN;
			}
			break;
			
			// Finding the rising edge, switch to falling edge scan
		case RISING_EDGE_SCAN:
			if (portf_status != 0)
			{
				pwmin_state = FALLING_EDGE_SCAN;
				pwmin_count_Up++;
			}
			break;
			
		case FALLING_EDGE_SCAN:
			// Found falling edge
			if (portf_status == 0)
			{
				cbi(TIMSK,OCIE2); //disable timer0 compare irq
				pwmin_read_flag = 1;  // Tell read function that read is complete
			}
			else  // No falling edge yet
			{
				// Count samples when PWM is high
				pwmin_count_Up++;
			}
			break;
	}
}
